package com.addtownumbers;

public class AddTowNumbers1 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2){
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        int carry = 0; //进位符
        ListNode dummy = new ListNode(0);
        ListNode pre = dummy;

        while (l1 != null && l2 != null){
            int sum = l1.val + l2.val + carry;
            carry = sum / 10;
            int num = sum % 10;
            ListNode node = new ListNode(num);
            dummy.next = node;

            dummy = dummy.next;
            l1 = l1.next;
            l2 = l2.next;
        }

        while (l1 != null){
            int sum = l1.val + carry;
            carry = sum / 10;
            int num = sum % 10;
            ListNode node = new ListNode(num);
            dummy.next = node;

            dummy = dummy.next;
            l1 = l1.next;
        }

        while (l2 != null){
            int sum = l2.val + carry;
            carry = sum / 10;
            int num = sum % 10;
            ListNode node = new ListNode(num);
            dummy.next = node;

            dummy = dummy.next;
            l2 = l2.next;
        }

        if (carry != 0){
            ListNode node = new ListNode(carry);
            dummy.next = node;
        }

        return pre.next;
    }
}
